var express = require('express');  //express模块，web开发框架
var path = require('path');        //解析文件路径
var favicon = require('serve-favicon');  // 网站icon图标
var logger = require('morgan');           //终端输出日志
var cookieParser = require('cookie-parser');  //格式化cookie数据
/**
 * express路由查找机制
 * 从上往下进行查找
 * 一个项目可以包含多个静态资源目录
 * 框架默认会加载index.html
 */
var bodyParser = require('body-parser');   // 格式化form表单post提交的数据

var index = require('./routes/index');
var users = require('./routes/users');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
//设置跨域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  if ('OPTIONS' === req.method) {
    //respond with 200
    res.send(200);
  }
  else {
  //move on
    next();
  }
});
var users=[
  {userName:'admin',psw:'123'},
  {userName:'xm',psw:'123'},
  {userName:'xh',psw:'123'},
  {userName:'xl',psw:'123'},
]
app.post('/api/v1/members/login',(req,res)=>{
  var user = req.body;
  if(user.userName){
    // Array.prototype.find 数组查找
    // 查找数组中第一个符合条件的数据
    var m = users.find((item)=>{
      return item.userName == user.userName;
    });
    if(m){
      if(m.psw == user.psw){
        res.json({status:'y',msg:'登陆成功'});
      }else{
        res.json({status:'n',msg:'密码错误'});
      }
    }else{
      res.json({status:'n',msg:'用户信息不存在'});
    }
  }else{
    res.json({status:'n',msg:'请输入用户名'});
    return;
  }
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
